package com.doge.walknovel.business

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.core.view.ViewCompat
import androidx.fragment.app.Fragment
import bolts.AppLinks
import com.doge.walknovel.analysis.AppsFlyerHelper
import com.doge.walknovel.analysis.analysisPurchase
import com.doge.wnpro.R
import com.doge.walknovel.business.home.NavigationLayout
import com.doge.walknovel.business.home.discover.DiscoverFragment
import com.doge.walknovel.business.home.genres.GenresFragment
import com.doge.walknovel.business.home.library.LibraryFragment
import com.doge.walknovel.business.home.profile.ProfileFragment
import com.doge.walknovel.core.BaseActivity
import com.doge.walknovel.core.BaseFragment
import com.doge.walknovel.core.base.Event
import com.doge.walknovel.core.base.events
import com.doge.wnpro.databinding.ActivityMainBinding
import com.doge.walknovel.deeplink.DeepLinkHelper
import com.doge.walknovel.payment.google.AppBillingClientFragment
import com.doge.walknovel.push.PushHelper
import com.doge.walknovel.utils.*

class MainActivity : BaseActivity() {
    private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        dispatchApplyWindowInsets()
        initialViews()
        events.observe(this, ::tryProcessEvent) // 0ms
        processIntent(intent, 0)
        UpgradeHelper.check()
        binding.viewPager.currentItem = 1
        AppBillingClientFragment.attach(this)

//        Handler(Looper.getMainLooper()).postDelayed({
//            analysisPurchase("testProductId11", "testOrderId11", "testOrderType11",
//                 "INR", "1594",100000)
//            analysisPurchase("testProductId22", "testOrderId22", "testOrderType22",
//                "INR", "150", 7800000)
//            analysisPurchase("testProductId33", "testOrderId33", "testOrderType33",
//                "INR", "155350", 6400000)
//            analysisPurchase("testProductId44", "testOrderId44", "testOrderType44",
//                "INR", "131550", 13800000)
//        }, 5000)

    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        processIntent(intent, 1)
    }

    private fun initialViews() {
        binding.viewPager.offscreenPageLimit = 4
        binding.viewPager.isUserInputEnabled = false
        binding.viewPager.adapter =
            object : androidx.viewpager2.adapter.FragmentStateAdapter(this) {
                override fun getItemCount(): Int = 4
                override fun createFragment(position: Int): Fragment {
                    return when (position) {
                        0 -> LibraryFragment()
                        1 -> DiscoverFragment()
                        2 -> GenresFragment()
                        3 -> ProfileFragment()
                        else -> BaseFragment()
                    }
                }
            }

        binding.navigation.attach(binding.viewPager)
        binding.navigation.setListener(object : NavigationLayout.Callback {
            override fun onItemClick(position: Int): Boolean {
                binding.viewPager.setCurrentItem(position, false)
                return false
            }

            override fun onItemClickAgain(position: Int) {
            }
        })
    }


    private fun tryProcessEvent(data: Pair<String, Any?>?) {
        if (data?.first == Event.SWITCH_MAIN_TAB) {
            if (data.second == 1) { // by add book
                binding.navigation.findViewById<View>(R.id.tabDiscover).performClick()
            }
        }
    }

    private fun dispatchApplyWindowInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { _, insets ->
            updateSystemWindowInsetsTop(insets.systemWindowInsets.top)
            insets
        }
    }

    private fun processIntent(intent: Intent?, flag: Int) {
        if (intent == null) return
        log("processIntent $intent")
        var handled = PushHelper.handleIntent(intent)
        if (!handled) {
            // {"targetUri":"app://www.walknovel.com/app?type\u003dnovelDetail\u0026novelId\u003d288"}
            // {"targetUri":"null"}
            val targetUri: Uri? = AppLinks.getTargetUrlFromInboundIntent(this, intent)
            handled = DeepLinkHelper.handleIntent(targetUri, flag + 10)
        }
        if (!handled) {
            DeepLinkHelper.handleIntent(intent.data, flag + 20)
        }
    }

    override fun onBackPressed() {
        if (!moveTaskToBack(false)) {
            super.onBackPressed()
        }
    }

    companion object {
        fun start(context: Context, wrap: Intent) {
            val intent = Intent(wrap)
            intent.setClass(context, MainActivity::class.java)
            context.startActivity(intent)
        }
    }
}
